package api;

import com.alibaba.fastjson.JSONObject;
import utils.HttpUtils;
import utils.TokenManager;

public class AccessToken {
    final static String accessTokenURI = "/aip/oauth/2.0/token";
    protected static String grantType = "client_credentials";         //默认值
    //    protected static String appId = "您的应用APPID";  //此参数，通过登录管理后台，创建应用处查看
//    protected static String apiKey = "您的应用ApiKey";
//    protected static String secretKey = "您的应用Secret Key";
    protected static String appId = "78066163";
    protected static String apiKey = "7effa16e7c2247e0b56b1527";
    protected static String secretKey = "d9dca9babb724f10807bfba980a61a34";
    //正式域名: "https://aip.ysaip.com"
    // 测试域名:"https://aiptest.ysaip.com";
    protected static String host = "https://aiptest.ysaip.com";

    static {
        TokenManager.getInstance().init(apiKey, () -> getAccessToken());
    }

    /**
     * 获取AccessToken
     *
     * @return
     */
    public static String getAccessToken() {
        String queryString = String.format("grant_type=%s&client_id=%s&client_secret=%s", grantType, apiKey, secretKey);
        String res = HttpUtils.doPost(host, accessTokenURI, queryString, null);
        JSONObject result = JSONObject.parseObject(res);
        if (result.containsKey("access_token")) {
            return result.get("access_token").toString();
        } else {
            System.out.println("获取token异常: " + result);
        }
        return null;
    }


    /**
     * 以缓存的方式使用TOKEN，这样获得更好的效率
     *
     * @return
     */
    public static String getCachedAccessToken() {
        return TokenManager.getInstance().getToken(apiKey);
    }


}
